package fr.obsmip.sedoo.server.service;

import java.util.ArrayList;
import java.util.Map;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import fr.obsmip.sedoo.client.service.UserService;
import fr.obsmip.sedoo.core.RBVApplication;
import fr.obsmip.sedoo.core.dao.UserDAO;
import fr.obsmip.sedoo.core.domain.RBVUser;
import fr.obsmip.sedoo.server.service.dtotool.UserDTOTools;
import fr.obsmip.sedoo.shared.domain.RBVUserDTO;
import fr.obsmip.sedoo.shared.exception.LoginException;
import fr.sedoo.commons.client.util.ServiceException;

public class UserServiceImpl extends RemoteServiceServlet implements
UserService {

	private static UserDAO dao = null;

	private static  Map<String,RBVUser> superAdmins;
	
	@Override
	public RBVUserDTO login(String login, String password) throws Exception 
	{
		initDao();
		RBVUser aux = superAdmins.get(login);
		if (aux != null)
		{
			if (aux.getPassword().compareTo(password)==0)
			{
				return UserDTOTools.toDTO(aux);
			}
			else
			{
				throw new LoginException("Uncorrect login/password");
			}
		}
		else
		{
			try
			{
				RBVUser aux2 = dao.login(login, password);
				return UserDTOTools.toDTO(aux2);
			}
			catch (Exception e)
			{
				throw new LoginException("Uncorrect login/password");
			}
		}
		
	}

	@Override
	public ArrayList<RBVUserDTO> findAll() throws ServiceException {
		initDao();
		try
		{
			return UserDTOTools.toDTOList(dao.findAll());
		}
		catch (Exception e)
		{
			throw new ServiceException(e);
		}
	}

	@Override
	public void delete(RBVUserDTO user) throws ServiceException {
		initDao();
		try
		{
			dao.delete(user.getId());
		}
		catch (Exception e)
		{
			throw new ServiceException(e);
		}
	}

	@Override
	public RBVUserDTO edit(RBVUserDTO user) throws ServiceException {
		return save(user);
	}

	@Override
	public RBVUserDTO create(RBVUserDTO user) throws ServiceException {
		return save(user);
	}
	
	private RBVUserDTO save(RBVUserDTO user) throws ServiceException {
		initDao();
		try
		{
			RBVUser savedUser = dao.save(UserDTOTools.fromDTO(user));
			return UserDTOTools.toDTO(savedUser);
		}
		catch (Exception e)
		{
			throw new ServiceException(e);
		}	
		
	}

	private void initDao() {
		if (superAdmins == null)
		{
			superAdmins = RBVApplication.getInstance().getSuperAdmins();
		}
		
		
		if (dao == null)
		{
			dao = RBVApplication.getInstance().getUserDAO();
		}
	}
	
}

